package mysql

import (
	"gorm.io/gorm"
	"novel-kit/novelrpc/novelrpc"
)

type Novel struct {
	gorm.Model
	NovelName  string `gorm:"type:varchar(50);not null;comment:'小说名称'"`
	Content    string `gorm:"type:varchar(500);not null;comment:'小说简介'"`
	NovelType  string `gorm:"type:varchar(50);not null;comment:'小说分类'"`
	NovelImage string `gorm:"type:varchar(500);not null;comment:'小说封面'"`
	UserId     int    `gorm:"type:int;not null;comment:'用户id'"`
}

func (n *Novel) NovelAdd(db *gorm.DB) error {
	return db.Create(n).Error
}

func (n *Novel) FindNovelById(db *gorm.DB, id int64) error {
	return db.Where("id=?", id).First(n).Error
}

func NovelList(db *gorm.DB, in *novelrpc.NovelListRequest) []*novelrpc.NovelList {
	var novelList []*novelrpc.NovelList
	tx := db.Model(&Novel{}).Select("novels.id as novel_id,novel_type,novel_name,content,novel_image,head_image,nick_name").
		Joins("LEFT JOIN users ON novels.user_id=users.id")

	if in.NovelName != "" {
		tx.Where("novel_name like ?", "%"+in.NovelName+"%")
	}
	if in.NovelType != "" {
		tx.Where("novel_type like ?", "%"+in.NovelType+"%")
	}
	tx.Scopes(Paginate(int(in.Page), int(in.PageSize))).Find(&novelList)
	return novelList
}
